#!/bin/bash

if [[ $EUID -ne 0 ]]; then
	   echo "This script must be run as root" 1>&2
#	   exit 1
fi

if [ $# != 4 ]; then 
     echo "Usage: $0 PKG_NAME PKG_VER INFO_FILE PKG_PPP"
     exit
fi
cwd=$PWD

#Create temporary directories
TEMP="/tmp/.package_tool"
TEMP2="/tmp/.pkg_tool_tmp"
rm -rf $TEMP
mkdir $TEMP
rm -rf $TEMP2
mkdir $TEMP2
#cp -rf $4/* $TEMP
tar jxf $4 -C $TEMP
mkdir -p $TEMP/var/pkgs/ 2>>/dev/null

#Remove any older .info and .files files
rm -f $TEMP/var/pkgs/$1*.info
rm -f $TEMP/var/pkgs/$1*.files

#copy .info file
grep -v Size $3 >$TEMP/var/pkgs/${1}-$2-imx.info
cd $TEMP
size=`du -ck ./ |grep "total"|awk 'BEGIN {FS=" "}{print $1}'`
echo "Size: "$size >>var/pkgs/${1}-$2-imx.info
tar cf $TEMP2/$1.tar *
tar -tvf $TEMP2/$1.tar >$TEMP2/$1.files

#Create .files file
for line in `cat $TEMP2/$1.files|awk 'BEGIN{FS=" "}{print $6}'`
do
     if [ -f $line ] && [ ! -L $line ] ;then
          md5=`md5sum $line|awk 'BEGIN{FS=" "}{print $1}'`
          f_size=`ls -l $line|awk 'BEGIN{FS=" "}{print $5}'`
     else
          md5="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
          f_size="0"
     fi     
     echo $md5" "$f_size" /"$line>>var/pkgs/${1}-$2-imx.files
done

#Add .files file
tar --append var/pkgs/${1}-$2-imx.files -f $TEMP2/$1.tar
bzip2 $TEMP2/$1.tar
mv $TEMP2/$1.tar.bz2 $cwd/${1}-$2-imx.ppp
cd $cwd             

#cleanup
rm -rf $TEMP
rm -rf $TEMP2
